<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * An instance of this class will be returned by
 * DMDataStoreFactory::getDataStore() when pdo_sqlite is the current data store.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMSQLiteDataStore extends DMPDODataStore implements DMDataStore {

	private static $instance;

	/** @var PDO handle */
	protected $dbcon;
	/** @var string PDO driver name */
	protected $driver = "pdo_sqlite";
	/** @var string Pathname of the SQLite database file */
	private $path;

	public function __sleep() {
		return array('driver', 'path');
	}

	/**
	 * Destroys the current Singleton object (not all your data)
	 * @return void
	 */
	public static function destroyInstance() {
		self::$instance = null;
	}

	/**
	 * @return self object
	 */
	public static function getInstance() {
		if (!self::$instance instanceof self) {
			self::$instance = new self;
		}
		return self::$instance;
	}

	protected function __construct() {
		DMDataStoreFactory::setDataStore('pdo_sqlite');
	}

	/**
	 * @return PDO handle
	 * @throws DMPDOException
	 */
	public function getConnection() {
		if (!$this->dbcon) {
			try {
				$this->dbcon = @new PDO(sprintf('sqlite:%s', $this->getPath()));
				$this->dbcon->setAttribute(PDO::ATTR_ERRMODE,
					PDO::ERRMODE_EXCEPTION);
				$this->createTables();
			} catch (PDOException $e) {
				$e = new DMPDOException($e);
				throw $e;
			}
		}
		return $this->dbcon;
	}

	/**
	 * @return Boolean
	 */
	public function databaseExists() {
		if (!file_exists($this->getPath())) {
			return false;
		}
	}

	/**
	 * @return string
	 */
	public function getPath() {
		if (!$this->path) {
			$this->path = DMConfigIni::getInstance()->getString(
					"dmbridge.database.sqlite.path");
			if (!$this->path) {
				$this->path
					= str_replace("\\", "/", DMConfigXML::getInstance()->getDataDir())
						. "/dmbridge.sqlite";
			}
		}
		return $this->path;
	}

	/**
	 * Overrides the path to the database file. If not explicitly set, the
	 * value from the config file will be used.
	 * 
	 * @param string path
	 */
	public function setPath($path) {
		$this->path = $path;
	}

	/**
	 * @return string One of the constants in DMDataStoreType
	 */
	public function getType() {
		return DMDataStoreType::PDO_SQLite;
	}

}
